#!/bin/bash

log_highlight() {
  echo -e "\033[43;31m"$1"$(tput sgr0)"
}

cmd_help() {
    echo -e "\nCommand help:"
    echo "$0 -h ---> command help"
    echo "$0 -r platform(cpu_host/cpu_dev) --->build tvm_runtime"
    echo -e "\nExample:"
    echo "    $0 -r cpu_host"
    echo -e "\nSupported platform:"
    echo "    cpu_host - tvm_runtime host running on cpu simulation"
    echo "    cpu_dev - tvm_runtime dev running on cpu simulation"
    exit
}

sdk_build() {
    if [ -d $build_dir ]; then
        rm -rf $build_dir
    fi
    mkdir -p $build_dir
    cp $1 $build_dir/config.cmake

    cd $build_dir
    cmake ../../ #-DCMAKE_BUILD_TYPE=Debug
    make -j

    ret=$?
    if [ $ret != 0 ];then
        log_highlight "\n***************************************************\nFailed to build  tvm_runtime:$runtime.\n***************************************************\n"
        exit 1
    fi
}

if [ $# -eq 0 ];then
    cmd_help
    exit
fi

work_dir=$(pwd)

#Get options.
while getopts 'r:h' OPT; do
    case $OPT in
        r)
            runtime_build=true
            runtime=$OPTARG
            ;;
        h)
            cmd_help
            ;;
        ?)
            cmd_help
            ;;
    esac
done

#Get desdk config.cmake.
if [ "$runtime_build" == true ]; then
    case $runtime in
        cpu_host)
            runtime_config="cmake/cpu_host_config.cmake"
            ;;
        cpu_dev)
            runtime_config="cmake/cpu_dev_config.cmake"
            ;;
        *)
            echo "Wrong runtime config name."
            cmd_help
            exit  1
            ;;
    esac
    build_dir="$work_dir/output/$runtime"
    sdk_build "$runtime_config"
fi

